package com.seek.inter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TSysmsg;
import com.seek.service.ReadService;
import com.seek.service.SysmsgService;
import com.seek.util.CommonUtil;

/**
 * 消息相关接口
 * @author lushuangteng
 *
 */
public class SysMsgInter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");
	private SysmsgService sysmsgService = (SysmsgService)SpringContextHolder.getBean("sysmsgService");
	public static int SYSMSG_PAGESIZE = 20;
	
	/**
	 * 获取消息推送列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getAppMsgList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String title = reqJson.getString("title");
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(title)){
			title = "%"+title+"%";
			where.append(" and a.title like ?");
			params.add(title);
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_sysmsg a where is_used=1 and a.company_id=? and a.type=1"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select a.id msgId,a.title,a.content,a.need_send_time needSendTime,(case when a.status>0 then 1 else 0 end) status,a.create_time createTime,");
		sb.append(" (select b.user_name from t_sys_user b where b.id=a.create_user_id) createName")
		  .append(" from t_sysmsg a where is_used=1 and a.company_id=? and a.type=1"+where.toString()+" order by a.id desc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 获取消息推送详情
	 * @param request
	 * @param reqJson
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getAppMsgDetail(HttpServletRequest request, JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		String msgId = reqJson.getString("msgId");
		
		try{
			if (CommonUtil.isEmpty(msgId)) {
				result.setStatus(1);
				result.setMessage("参数错误，请检查!");
				return result;
			}
			
			StringBuffer sb = new StringBuffer("select a.id msgId,a.title,a.content,a.need_send_time needSendTime ");
			sb.append(" from t_sysmsg a where is_used=1 and a.id=?");
			result.setStatus(0);
			result.setMessage("成功");
			result.setBody(readService.findOneMapBySql(sb.toString(), new Object[]{msgId}));
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
	/**
	 * 新增或编辑消息后的保存
	 */
	public ResultInfo saveAppMsg(HttpServletRequest request,JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		try{
			TSysmsg en = sysmsgService.save(reqJson);
			Map<String, Object> ret = new HashMap<String, Object>();
			ret.put("id", en.getId());
			result.setStatus(0);
			result.setMessage("成功");
			result.setBody(ret);
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
	/**
	 * app推送消息删除
	 * @param request
	 * @param reqJson
	 * @return
	 * @throws Exception
	 */
	public ResultInfo delAppMsg(HttpServletRequest request, JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		String msgId = reqJson.getString("msgId");
		try{
			if (CommonUtil.isEmpty(msgId)) {
				result.setStatus(1);
				result.setMessage("参数错误，请检查!");
				return result;
			}
			
			String sql = "update t_sysmsg set is_used=0 where id =?";
			sysmsgService.executeUpdate(sql,new Object[]{msgId});

			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
//	/**
//	 * 取得未读系统消息数量
//	 * @param request
//	 * @return
//	 * @throws Exception
//	 */
//	public ResultInfo getUnReadMsgCount(HttpServletRequest request,JSONObject reqJson) throws Exception {
//		ResultInfo result = new ResultInfo();
//		String uid = reqJson.getString("custId");
//		try{
//			// 根据uid从缓存中读取
//			String m = CacheUtil.getRedisData(CacheUtil.SYS_MSG_NUMBER_+uid);
//			int number = 0;
//			if (m != null){
//				number = CommonUtil.getIntValue(m);
//			}
//			
//			Map<String,Object> ret = new HashMap<String,Object>();
//			ret.put("sl", number);
//			result.setStatus(0);
//			result.setMessage("成功");
//			result.setBody(ret);
//			
//			return result;
//		}catch(Exception e){
//			logger.error("系统异常",e);
//			result.setStatus(1);
//			result.setMessage(e.getMessage());
//			return result;
//		}
//	}
//
//	/**
//	 * 取得系统消息列表
//	 * @param request
//	 * @return
//	 * @throws Exception
//	 */
//	@SuppressWarnings("unchecked")
//	public ResultInfo getMsgList(HttpServletRequest request,JSONObject reqJson) throws Exception {
//		ResultInfo result = new ResultInfo();
//		String uid = reqJson.getString("custId");
//		int pageNo = reqJson.getInteger("pageNo") == null ? 1:reqJson.getInteger("pageNo");
//		try{
//			if (pageNo < 1)
//				pageNo = 1;
//			StringBuffer sb = new StringBuffer("");
//			int startRow = (CommonUtil.getIntValue(pageNo) - 1) * (SYSMSG_PAGESIZE);
//			int endRow = SYSMSG_PAGESIZE;
//			
//			// 刷新客户消息缓存
//			CacheUtil.delRedisData(CacheUtil.SYS_MSG_NUMBER_+uid);
//			
//			// 更新消息为已读
//			String sql = "update t_sysmsg set status=1 where status=0 and recive_id=?";
//			interService.executeUpdate(sql,new Object[]{uid});
//
//			// 获取客户的消息内容
//			sb.append("select a.id msgId, a.type, a.title, a.content, a.create_time createTime, a.rel_id relId,b.logo imageUrl")
//			  .append(" from t_sysmsg a,t_sysmsg_typelogo b where a.type=b.type and (a.recive_id=-1 or a.recive_id=?)  and status<2");
//			sb.append(" order by a.id desc limit " + startRow + "," + endRow);
//			List<Map<String,Object>> data = interService.findMapBySql(sb.toString(),new Object[]{uid});
//			
//			result.setStatus(0);
//			result.setMessage("成功");
//			result.setBody(data);
//			
//			return result;
//		}catch(Exception e){
//			if(!"没有更多数据".equals(e.getMessage())) {
//				logger.error("系统异常",e);
//			}
//			result.setStatus(1);
//			result.setMessage(e.getMessage());
//			return result;
//		}
//	}
//	
//	/**
//	 *  消息删除
//	 */
//	public ResultInfo updateMsgStatus(HttpServletRequest request,JSONObject reqJson) throws Exception {
//		ResultInfo result = new ResultInfo();
//		String msgid = reqJson.getString("msgid");
//		try{
//			String sql = "update t_sysmsg set status=2 where id=?";
//			interService.executeUpdate(sql,new Object[]{msgid});
//			
//			result.setStatus(0);
//			result.setMessage("成功");
//			return result;
//		}catch(Exception e){
//			logger.error("系统异常",e);
//			result.setStatus(1);
//			result.setMessage(e.getMessage());
//			return result;
//		}
//	}
}
